const app = getApp();

var playTimeInterval
var recordTimeInterval;
const mp3Recorder = wx.getRecorderManager();
const mp3RecoderOptions = {
  duration: 600000,
  sampleRate: 16000,
  numberOfChannels: 1,
  encodeBitRate: 48000,
  format: 'mp3',
  frameSize: 50,
};
const mp3Player = wx.createInnerAudioContext()
var pageSelf = undefined;

mp3Recorder.onError(() => {
  console.log('error')
})

mp3Recorder.onStart(() => {
  console.log('recorder start')
})

Page({
  data: {
    taskId: null,
    currentTaskIndex: 0,
    totalCount: null,
    taskItems: [],
    recording: false,
    playing: false,
    hasRecord: false,
    recordTime: 0,
    showModal: false,
    layerHidden: true,
    isCommit: false
  },

  /**
   * 上传任务
   */
  uploadCurrentItem: function (_this) {
    if (_this.data.hasRecord) {
      wx.showLoading({
        mask: true
      })
      wx.uploadFile({
        url: app.globalData.apiDomain + 'crowdsource/task/uploadFileForSubject',
        header: { 'Content-Type': 'multipart/form-data', 'token': app.globalData.token },
        filePath: _this.data.taskItems[_this.data.currentTaskIndex].speechFilePath,
        name: 'file',
        formData: {
          "projectTypeId": 2,
          "subjectId": _this.data.taskItems[_this.data.currentTaskIndex].id,
          "duration": _this.data.taskItems[_this.data.currentTaskIndex].duration,
        },
        success: function (res) {
          var data = JSON.parse(res.data);
          if (data.status === 'ok') {
            /*
            音频文件上传成功后更新视频文件地址
            _this.data.taskItems[_this.data.currentTaskIndex].speechFilePath = data.object
            _this.setData({
              taskItems: _this.data.taskItems,
            });
            */
          } else if (data.status == 'error') {
            wx.showModal({
              content: '不好，挂了！管理员哥哥正在赶来~',
              showCancel: false
            })
          } else {
            wx.showModal({
              content: data.message,
              showCancel: false
            })
          }
        },
        fail: function (res) {
          wx.showModal({
            content: '不好，挂了！管理员哥哥正在赶来~',
            showCancel: false
          })
        },
        complete: function (res) {
          wx.hideLoading();
        }
      })
    } else {
      wx.showModal({
        content: '呀，这一条还没录呢，录完再走吧！',
        showCancel: false,
      })
    }
  },
  checkSwitch: function (taskItem) {
    if (this.data.recording) {
      wx.showModal({
        content: '呀，这一条正在录呢，录完再走吧！',
        showCancel: false
      });
      return false;
    }

    if (!taskItem.speechFilePath) {
      wx.showModal({
        content: '呀，这一条还没录呢，录完再走吧！',
        showCancel: false
      });
      return false;
    }
    return true;
  },
  /**
   * 确认提交
   */
  commitTask: function () {

    var _this = this;
    let taskItem = _this.data.taskItems[_this.data.currentTaskIndex];
    if (!_this.checkSwitch(taskItem)) {
      return;
    }

    wx.request({
      url: app.globalData.apiDomain + 'crowdsource/task/commitTask/' + _this.data.taskId,
      method: 'POST',
      header: { 'Content-Type': 'application/json', 'token': app.globalData.token },
      success: function (res) {
        let data = res.data;
        if (data.status === 'ok') {

          _this.setData({
            isCommit: true
          });
          wx.showModal({
            content: '任务提交成功，小姐姐们会尽快审核的，请耐心等待呦！',
            showCancel: false,
            success: function (e) {
              wx.switchTab({
                url: '../../my_tasks/task_list/task_list'
              })
            }
          })

        } else {
          app.responseCheck(_this, data, "pages/public_tasks/do_task/do_task?taskId=" + _this.data.taskId);
        }
      },
      fail: function (e) {
        wx.showModal({
          content: '不好，挂了！管理员哥哥正在赶来~',
          showCancel: false
        })
      }
    })

  },
  /**
   * 任务切换 - 上一条
   */
  taskSwitchPrevious: function () {

    var _this = this;
    let taskItem = _this.data.taskItems[_this.data.currentTaskIndex];
    if (!this.checkSwitch(taskItem)) {
      return;
    }

    if (_this.data.taskItems[_this.data.currentTaskIndex - 1]) {
      _this.setData({
        currentTaskIndex: _this.data.currentTaskIndex - 1,
        hasRecord: true,
        recordTime: _this.data.taskItems[_this.data.currentTaskIndex - 1].duration
      });
      return false;
    }

    wx.request({
      url: app.globalData.apiDomain + 'crowdsource/task/previousSubject',
      data: {
        'taskId': _this.data.taskId,
        'projectTypeId': 2,
        'subjectId': taskItem.id,
        'currentOrder': taskItem.order,
      },
      header: { 'Content-Type': 'application/json', 'token': app.globalData.token },
      success: function (res) {
        let data = res.data;
        if (data.status === 'ok') {
          var index = data.object.order - 1;
          _this.data.taskItems[index] = data.object;

          //是否有录音
          let hasRecord = false;
          if (data.object.speechFilePath) {
            hasRecord = true;
          }

          _this.setData({
            currentTaskIndex: index,
            taskItems: _this.data.taskItems,
            hasRecord: hasRecord,
            recordTime: _this.data.taskItems[index].duration
          });
        } else {
          app.responseCheck(_this, data, "pages/public_tasks/do_task/do_task?taskId=" + _this.data.taskId);
        }
      },
      fail: function (e) {
        wx.showModal({
          content: '不好，挂了！管理员哥哥正在赶来~',
          showCancel: false
        })
      }
    })
  },
  /**
   * 任务切换 - 下一条
   */
  taskSwitchNext: function () {

    var _this = this;
    let taskItem = _this.data.taskItems[_this.data.currentTaskIndex];
    if (!this.checkSwitch(taskItem)) {
      return;
    }

    if (_this.data.taskItems[_this.data.currentTaskIndex + 1]) {
      //是否有录音
      let hasRecord = false;
      if (_this.data.taskItems[_this.data.currentTaskIndex + 1].speechFilePath) {
        hasRecord = true;
      }

      _this.setData({
        currentTaskIndex: _this.data.currentTaskIndex + 1,
        hasRecord: hasRecord,
        recordTime: _this.data.taskItems[_this.data.currentTaskIndex + 1].duration
      });
      return false;
    }

    wx.request({
      url: app.globalData.apiDomain + 'crowdsource/task/nextSubject',
      data: {
        'taskId': _this.data.taskId,
        'projectTypeId': 2,
        'subjectId': taskItem.id,
        'currentOrder': taskItem.order,
      },
      header: { 'Content-Type': 'application/json', 'token': app.globalData.token },
      success: function (res) {
        let data = res.data;
        if (data.status === 'ok') {
          var index = data.object.order - 1;
          _this.data.taskItems[index] = data.object;

          //是否有录音
          let hasRecord = false;
          if (data.object.speechFilePath) {
            hasRecord = true;
          }

          _this.setData({
            currentTaskIndex: index,
            taskItems: _this.data.taskItems,
            hasRecord: hasRecord,
            recordTime: data.object.duration
          });

        } else {
          app.responseCheck(_this, data, "pages/public_tasks/do_task/do_task?taskId=" + _this.data.taskId);
        }
      },
      fail: function (e) {
        wx.showModal({
          content: '不好，挂了！管理员哥哥正在赶来~',
          showCancel: false
        })
      }
    })
  },

  clear: function () {

    clearInterval(playTimeInterval)
    mp3Player.stop();

    if (this.data.recording) {
      mp3Recorder.stop();
    }

    this.setData({
      playing: false,
      hasRecord: false,
      recordTime: 0,
    })
  },
  startRecord_m: function () {
    
    mp3Recorder.start(mp3RecoderOptions);

    mp3Recorder.onError(() => {
      wx.openSetting({
        success: function (res) {
          if(!res.authSetting['scope.record']) {
            console.log("未设置录音授权");
          }
        }
      })
    })
    
  },
  stopRecord_m: function () {
    console.log('停止录音');
    mp3Recorder.stop();
  },
  startPlay_m: function () {
    mp3Player.obeyMuteSwitch = false;
    mp3Player.src = this.data.taskItems[this.data.currentTaskIndex].speechFilePath;
    mp3Player.play();
  },
  stopPlay_m: function () {
    mp3Player.stop();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    console.log('onload');
    this.setData({
      taskId: options.id,
    });

    wx.setNavigationBarTitle({
      title: options.projectName ? options.projectName : ''
    })

    pageSelf = this;
    var _this = this;

    //start recorder
    mp3Recorder.onStart(() => {
      pageSelf.setData({
        recording: true,
        recordTime: 0,
      })
      recordTimeInterval = setInterval(function () {
        var recordTime = pageSelf.data.recordTime += 1
        pageSelf.setData({
          recordTime: recordTime
        })
      }, 1000)
    })
    // stop recorder
    mp3Recorder.onStop((res) => {
      clearInterval(recordTimeInterval);

      this.data.taskItems[this.data.currentTaskIndex].speechFilePath = res.tempFilePath;
      this.data.taskItems[this.data.currentTaskIndex].duration = Math.round(res.duration / 1000);

      this.setData({
        taskId: options.id,
        recording: false,
        hasRecord: true,
        taskItems: this.data.taskItems,
      });

      this.uploadCurrentItem(this);
    })
    mp3Recorder.onError(() => {

    })

    //start player
    mp3Player.onPlay(() => {
      this.setData({
        playing: true
      })
    })
    mp3Player.onStop(() => {
      this.setData({
        playing: false
      })
    })
    mp3Player.onEnded(() => {
      this.setData({
        playing: false
      })
    })
    mp3Player.onError((res) => {
      this.setData({
        playing: false
      })
      wx.showModal({
        title: '播放音频失败',
        content: res.errMsg,
      })
    })
    //end player

    wx.request({
      url: app.globalData.apiDomain + 'crowdsource/task/doTask',
      data: {
        'taskId': _this.data.taskId,
        'projectTypeId': 2
      },
      header: { 'Content-Type': 'application/json', 'token': app.globalData.token },
      success: function (res) {
        let data = res.data;

        if (data.status === 'ok') {
          if (!data.object.speech) {
            wx.showModal({
              title: '',
              content: '任务竟然不存在！还是去看看别的吧~ ',
              showCancel: false
            })
          }
          var index = data.object.speech.order - 1;
          _this.data.taskItems[index] = data.object.speech;
          let hasRecord = false;
          if (data.object.speech.speechFilePath) {
            hasRecord = true;
          }

          _this.setData({
            currentTaskIndex: index,
            taskItems: _this.data.taskItems,
            totalCount: data.object.taskCount,
            hasRecord: hasRecord,
            recordTime: data.object.speech.duration
          });

        } else if (data.status == 'error') {
          wx.showModal({
            content: '不好，挂了！管理员哥哥正在赶来~',
            showCancel: false
          })
        } else {
          wx.showModal({
            content: data.message,
            showCancel: false
          })
        }
      },
      fail: function (e) {
        wx.showModal({
          content: '不好，挂了！管理员哥哥正在赶来~',
          showCancel: false
        })
      }
    })
  },
  hideModal: function () {
    wx.showModal({
      title: 'test1',
      content: '',
    })
    this.setData({
      showModal: false
    })
  },
  closeBtn: function () {
    console.log('closeBtn');
    this.setData({
      layerHidden: false
    });
  },
  cancelBtn: function () {
    this.setData({
      layerHidden: true
    })
  },
  leaveBtn: function () {
    wx.switchTab({
      url: '../task_list/task_list'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //this.clear();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.clear();

    // 正常提交不提示
    if (!this.data.isCommit) {
      wx.showModal({
        content: '任务未完成，可以从我的任务重新进入',
        showCancel: false
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})